package com.iwayin.core.utils;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 转换imgurl为完全路径的url的类
 * 
 * @author xiaobo.feng<xiaobo.feng@foxmail.com>
 * 
 *         2011-8-12
 */
public class ImageUtil {
	public static void main(String[] args) {
	//	abscut("D:/jingxuan6.jpg", 20, 20, 20, 20);
		try {
			
				//ImageUtil.changeImg("D:/wayin/ wayin-demo/iwayin-web/target/iwayin-web/yoaskPic/"+"Img320808028.jpg", "http://photocdn.sohu.com/20110928/Img320808028.jpg", 265, 265, "jpg");
		//	ImageUtil.abscut("http://photocdn.sohu.com/20110928/Img320808028.jpg", 184,393, 121, 121,"D:/wayin/ wayin-demo/iwayin-web/target/iwayin-web/yoaskPic/"+"Img320808028.jpg", "http://photocdn.sohu.com/20110928/Img320808028.jpg");
			} 
		//BufferedImage bi = ImageIO.read(new File("http://s1.hao123img.com/index/images/logo.png?v=1.1"));
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 按坐标切割图片
	 * 
	 * @param srcImageFile
	 *            源图片
	 * @param x
	 *            x坐标
	 * @param y
	 *            y坐标
	 * @param destWidth
	 *            宽
	 * @param destHeight
	 *            长
	 * @author gyf
	 */
	public static File abscut(File uploadPic, int x, int y, int destWidth, int destHeight,String path,String imagePath) {
		try {
			Image img;
			ImageFilter cropFilter;
			 InputStream inputStream =new FileInputStream(uploadPic);
			 BufferedInputStream source = new BufferedInputStream(inputStream);
			 BufferedImage bi =ImageIO.read(source);
			// 读取源图像
			//URL url = new URL(imagePath);
            //载入图片到输入流
			//BufferedInputStream bis = new BufferedInputStream(url.openStream());
			//BufferedImage bi =ImageIO.read(bis);
			//BufferedImage bi = ImageIO.read(new File(srcImageFile));
			int srcWidth = bi.getWidth(); // 源图宽度
			int srcHeight = bi.getHeight(); // 源图高度
			System.out.println("srcWidth= " + srcWidth + "\tsrcHeight= " + srcHeight);
			if (srcWidth >= destWidth && srcHeight >= destHeight) {
				Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
				// 改进的想法:是否可用多线程加快切割速度
				// 四个参数分别为图像起点坐标和宽高
				// 即: CropImageFilter(int x,int y,int width,int height)
				cropFilter = new CropImageFilter(x, y, destWidth, destHeight);
				img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
				BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
				Graphics g = tag.getGraphics();
				g.drawImage(img, 0, 0, null); // 绘制缩小后的图
				g.dispose();
				// 输出为文件
				boolean isSuccess=ImageIO.write(tag, "JPEG", new File(path));
				if(isSuccess){
					File newFile =new File(path);
					return newFile;
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 等比例压缩图片
	 * 
	 * @param imgPath
	 * @param width
	 * @param height
	 * @param extName
	 * @throws Exception
	 * @author gyf
	 */
	public static File changeImg(String savePath,String imagePath, int width, int height, String extName) throws Exception {
		Image img;
		ImageFilter cropFilter;
		// 读取源图像
		URL url = new URL(imagePath);
		// 载入图片到输入流
		BufferedInputStream bis = new BufferedInputStream(url.openStream());
		// BufferedImage bi =ImageIO.read(bis);
		// InputStream inputStream =new FileInputStream(uploadPic);
		// BufferedInputStream source = new BufferedInputStream(inputStream);
		File newFile = new File(savePath);
		String imageFormat = extName;

		// 图片的缩放比例计算
		Image src = ImageIO.read(bis);

		BufferedImage tag = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(
				src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,
				null); // 绘制缩小后的图
		FileOutputStream newimage = new FileOutputStream(newFile);

		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
		encoder.encode(tag);
		newimage.close();

		return newFile;

	}
	public static File changeImg2(String savePath,File uploadFile, int width, int height, String extName) throws Exception {
		InputStream inputStream =new FileInputStream(uploadFile);
		BufferedInputStream source = new BufferedInputStream(inputStream);
		File newFile = new File(savePath);
		// 图片的缩放比例计算
		Image src = ImageIO.read(source);

		BufferedImage tag = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(
				src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,
				null); // 绘制缩小后的图
		FileOutputStream newimage = new FileOutputStream(newFile);

		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
		encoder.encode(tag);
		newimage.close();

		return newFile;

	}

	/**
	 * 转成完全路径
	 * 
	 * @param outsideKey
	 * @param imgUrl
	 * @return
	 */
	public static String getFullImageUrl(String prefix, String outsideKey, String imgUrl) {
		// String prefix = "http://image.taobao.net/bao/uploaded";

		if (imgUrl == null) {
			return null;
		}

		imgUrl = imgUrl.trim();

		String postfix = "_sum.jpg";

		String regStr = "/i";
		boolean bb = imgUrl.startsWith(regStr);
		boolean cc = imgUrl.startsWith("/");

		if (cc) {
			if (bb) {
				String ns = imgUrl.split("/")[1].substring(1);
				if (ns.length() == 1) {
					ns = "img0" + ns;
				} else {
					ns = "img" + ns;
				}
				prefix = prefix.replaceFirst("image", ns);
			}
			imgUrl = prefix + imgUrl + postfix;
		} else {
			imgUrl = prefix + "/" + imgUrl + postfix;
		}
		return imgUrl;
	}

	public static String getFullImageUrl(String imgUrl) {
		return getFullImageUrl("http://image.taobao.com/bao/uploaded", "taobao", imgUrl);
	}

	public static String getFullImageUrl(String prefix, String imgUrl) {
		return getFullImageUrl(prefix, "taobao", imgUrl);
	}

	/**
	 * target image file name
	 * 
	 * @return image file name
	 * @author gyf
	 */
	public static String fileNameStr() {
		StringBuffer fileName = new StringBuffer();
		fileName.append(DateTimeUtil.getCurrDateTimeStr()).append(System.currentTimeMillis()).append(PasswordUtil.getRandomOperRandomKey());
		fileName = new StringBuffer(fileName.toString().replace(":", ""));
		return fileName.toString().replace(" ", "");
	}
}
